﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.DB;

namespace ModelValidation.AreaRatioWindowToWall
{
	internal class RelationWindowToWall
	{
		public static Dictionary<int, List<FamilyInstance>> DoorAndWindowList
		{
			get
			{
				return RelationWindowToWall.m_DoorAndWindowList;
			}
		}

		internal RelationWindowToWall(Autodesk.Revit.DB.Document doc)
		{
			RelationWindowToWall.m_Doc = doc;
			RelationWindowToWall.m_DoorAndWindowList = new Dictionary<int, List<FamilyInstance>>();
		}

		public static void RelationWindowToWallInit()
		{
			if (RelationWindowToWall.m_DoorAndWindowList.Count > 0)
			{
				RelationWindowToWall.m_DoorAndWindowList.Clear();
			}
			RelationWindowToWall.GetInstanceInDoc(RelationWindowToWall.m_Doc);
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(RelationWindowToWall.m_Doc);
			ElementClassFilter elementClassFilter = new ElementClassFilter(typeof(RevitLinkInstance));
			foreach (Element element in filteredElementCollector.WherePasses(elementClassFilter).ToElements())
			{
				RelationWindowToWall.GetInstanceInDoc((element as RevitLinkInstance).GetLinkDocument());
			}
		}

		private static void GetInstanceInDoc(Autodesk.Revit.DB.Document doc)
		{
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
			ElementClassFilter elementClassFilter = new ElementClassFilter(typeof(FamilyInstance));
			foreach (Element element in filteredElementCollector.WherePasses(elementClassFilter).ToElements())
			{
				FamilyInstance familyInstance = element as FamilyInstance;
				Category category = familyInstance.Category;
				if (category.Id.IntegerValue == -2000023 || category.Id.IntegerValue == -2000014)
				{
					RelationWindowToWall.AddFamilyIntanceToDic(familyInstance);
				}
			}
		}

		private static void AddFamilyIntanceToDic(FamilyInstance inputIns)
		{
			int integerValue = inputIns.Host.Id.IntegerValue;
			if (!RelationWindowToWall.m_DoorAndWindowList.Keys.Contains(integerValue))
			{
				RelationWindowToWall.m_DoorAndWindowList.Add(integerValue, new List<FamilyInstance>());
			}
			if (!RelationWindowToWall.m_DoorAndWindowList[integerValue].Contains(inputIns))
			{
				RelationWindowToWall.m_DoorAndWindowList[integerValue].Add(inputIns);
			}
		}

		private static Document m_Doc;

		private static Dictionary<int, List<FamilyInstance>> m_DoorAndWindowList;
	}
}
